<!DOCTYPE html>
<html lang="en">

<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <title>壹果企画(北京)科技有限公司-销售系统</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <link rel="stylesheet" type="text/css" href="../../css/cloud-admin.css">
  <link rel="stylesheet" type="text/css" href="../../css/themes/default.css" id="skin-switcher">
  <link rel="stylesheet" type="text/css" href="../../css/responsive.css">
  <!-- STYLESHEETS -->
  <!--[if lt IE 9]><script src="js/flot/excanvas.min.js"></script><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script><![endif]-->
  <link href="../../font-awesome/css/font-awesome.min.css" rel="stylesheet">
  <!-- ANIMATE -->
  <link rel="stylesheet" type="text/css" href="../../css/animatecss/animate.min.css" />


  <!-- UNIFORM -->
  <link rel="stylesheet" type="text/css" href="../../js/uniform/css/uniform.default.min.css" />
  <!-- datatable -->
  <link rel="stylesheet" href="../../js/datatables/datatable.css">
  <!-- WIZARD -->
  <link rel="stylesheet" type="text/css" href="../../js/bootstrap-wizard/wizard.css" />
  <link rel="stylesheet" type="text/css" href="../../js/select2/select2.min.css" />


</head>

<body>


  <!-- PAGE -->
  <section id="page">
    <div class="modal fade" id="box-config" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <form id="form_account">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
              <h4 class="modal-title">填写收件信息</h4>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <label class="control-label col-md-3" style="line-height:34px;">
                  <span class="required">*</span>姓名：
                </label>
                <div class="col-md-4">
                  <input type="text" class="form-control" name="receiver" placeholder="请输入姓名"/>
                  <span class="error-span"></span>
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-md-3" style="line-height:34px;">
                  <span class="required">*</span>电话号码：
                </label>
                <div class="col-md-4">
                  <input name="telPhone" type="text" placeholder="请输入电话号码" class="form-control"/>
                  <span class="error-span"></span>
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-md-3" style="line-height:34px;">
                  <span class="required">*</span>省：
                </label>
                <div class="col-md-4">
                  <select name="provinceName" id="provinceName" style="width: 200px;">
                  </select>
                  <!-- <input type="text" class="form-control" name="provinceName" placeholder="请输入省份"/> -->
                  <span class="error-span"></span>
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-md-3" style="line-height:34px;">
                  <span class="required">*</span>市：
                </label>
                <div class="col-md-4">
                  <select name="cityName" id="cityName" style="width: 200px;">
                  </select>
                  <!-- <input type="text" class="form-control" name="cityName" placeholder="请输入市"/> -->
                  <span class="error-span"></span>
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-md-3" style="line-height:34px;">
                  <span class="required">*</span>区：
                </label>
                <div class="col-md-4">
                  <select name="areaName" id="areaName" style="width: 200px;">
                  </select>
                  <!-- <input type="text" class="form-control" name="areaName" placeholder="请输入区"/> -->
                  <span class="error-span"></span>
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-md-3" style="line-height:34px;">
                  <span class="required">*</span>详细地址：
                </label>
                <div class="col-md-4">
                  <textarea name="address" placeholder="请输入详细地址" class="form-control" style="width:280px;resize:none;"></textarea>
                  <span class="error-span"></span>
                </div>
              </div>
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
              <button type="button" class="btn btn-success bt-save">确定</button>
            </div>
          </div>
        </div>
      </form>
    </div>
    <div class="container">
      <div class="row">
        <div id="content" class="col-lg-12">
          <!-- PAGE HEADER-->
          <div class="row">
            <div class="col-sm-12">
              <div class="page-header">
                <!-- STYLER -->
                <!-- /STYLER -->

                <div class="clearfix">
                  <h3 class="content-title pull-left">欢迎登录壹果销售系统-销售录入</h3>
                  <a class="btn btn-warning sale_report" style="margin-left:50px;float: right;margin-top:5px">销售统计</a>
                  <a class="btn btn-primary" href="product_list.html" style="float: right;margin-top:5px;display:none">商品管理</a>

                </div>

              </div>
            </div>
          </div>
          <!-- /PAGE HEADER -->
          <div class="row" style=" font-size: 28px;">
            <div class="form-group">
              <label class="control-label col-md-2" style="text-align: right">展会名称：</label>
              <div class="col-md-8">
                <input type="text" class="form-control width-50" style="height: 40px" name="actionName" readonly="readonly" maxlength="50"
                />

              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-2" style="text-align: right">商品条码：</label>
              <div class="col-md-8">
                <input type="text" class="form-control width-50" style="height: 40px" name="skuCode" onfocus="this.select()" onmouseover="this.onfocus()"
                  placeholder="请输入商品条码" maxlength="50" />

              </div>
            </div>
          </div>
          <div class="row" style="font-size: 24px;display:flex">
            <label class="control-label col-md-2" style="text-align: right;">总数量：</label>
            <span class="totalAmount" style="color: red; min-width: 50px;">0</span>
            <label class="control-label" style="text-align: right;min-width: 140px;">总金额：</label>
            <span class="totalMoney" style="color: red; min-width: 100px;">0</span>
            <label class="control-label " style="text-align: right;min-width: 140px;">支付方式：</label>
            <div class="col-md-1 inline">
              <select name="payType" id="payway">
                <option value='Cash'>现金&nbsp;&nbsp;</option>
                <option value='Alipay'>支付宝</option>
                <option value='WeChat'>微信&nbsp;&nbsp;</option>
              </select>
            </div>
            <label class="control-label" style="text-align: right;min-width: 140px;">提取方式：</label>
            <div class="col-md-1 inline">
              <select name="pickWay" id="pickway">
                <option value='SinceLift'>自提</option>
                <option value='Logistics'>快递</option>
              </select>
            </div>
            <!-- <label class="control-label col-md-2" style="text-align: right">付款方式：</label>
				<div><input type="radio" name="payType" checked="checked" value="0">有赞收钱<input type="radio" name="payType" style="margin-left:10px" value="1">现金</div>
				 -->
            <a class="btn btn-success bt-saveOrder" style="height:38px">提交订单</a>
          </div>
          <!-- <div class="row" style=" font-size: 28px;margin-top: 20px;">
            <div class="form-group">
              <label class="control-label col-md-2" style="text-align: right">展会名称：</label>
              <div class="col-md-8">
                <input type="text" class="form-control width-50" style="height: 40px" name="actionName"
                />
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-2" style="text-align: right">商品条码：</label>
              <div class="col-md-8">
                <input type="text" class="form-control width-50" style="height: 40px" name="skuCode" placeholder="请输入商品条码" maxlength="50" />
              </div>
            </div>
          </div> -->
          <div class="row" style="text-align:left; font-size: 14px">

            <table class="datatable table table-striped table-bordered table-hover dataTable no-footer">
              <thead>
                <tr>
                  <th width="5%">SKU编码</th>
                  <th width="10%">商品名称</th>
                  <th width="5%">尺码</th>
                  <th width="5%">销售单价</th>
                  <th width="5%">数量</th>
                  <th width="5%">库存</th>
                  <th width="5%">操作</th>
                </tr>
              </thead>
              <tbody>

              </tbody>
            </table>
          </div>

        </div>

      </div>
      <!-- /CONTENT-->
    </div>

    </div>
  </section>


  <!--/PAGE -->
  <!-- JQUERY -->
  <script src="../../js/jquery/jquery-2.0.3.min.js"></script>

  <!-- BOOTSTRAP -->
  <script src="../../bootstrap-dist/js/bootstrap.min.js"></script>
  <script src="../../js/city.js"></script>
  <!--bootbox-->
  <script type="text/javascript" src="../../js/bootbox/bootbox.min.js"></script>
  <script type="text/javascript" src="../../js/select2/select2.min.js"></script>
  <script src="../../js/jquery-validate/jquery.validate.min.js"></script>
  <script src="../../js/common.js"></script>
  <script>
    $(function () {
      var provinceName = '',
          cityName = '';
      $("#provinceName").select2();
      $("#cityName").select2();
      $("#areaName").select2();
      $("#provinceName").change(function (e) {
        var val = $(this).val();
        createCity(val);
      });
      $("#cityName").change(function (e) {
        var val = $(this).val();
        createAreaName(val);
      });
      var provinceNameStr = '';
      provinceList.forEach(function(item) {
        provinceNameStr += "<option value=" + item.provinceName + ">" + item.provinceName + "</option>"
      });
      $("#provinceName").append(provinceNameStr);
      $("#provinceName").select2('val', provinceList[0].provinceName);
      createCity(provinceList[0].provinceName);
      function createCity (provinceNa) {
        provinceName = provinceNa;
        $("#cityName").empty();
        var cityNameStr = '',
            cityList = [];
        provinceList.forEach(function(item) {
          if (item.provinceName == provinceName) {
            cityList = item.cityList;
            cityList.forEach(function (ele) {
              cityNameStr += "<option value=" + ele.cityName + ">" + ele.cityName + "</option>"
            });
            return false;
          }
        });
        $("#cityName").append(cityNameStr);
        $("#cityName").select2('val', cityList[0].cityName);
        createAreaName(cityList[0].cityName);
      }
      function createAreaName (cityN) {
        cityName = cityN;
        $("#areaName").empty();
        var areaNameString = '',
            areaList = [];
        provinceList.forEach(function(item) {
          if (item.provinceName == provinceName) {
            item.cityList.forEach(function(ele) {
              if (ele.cityName == cityName) {
                areaList = ele.areaList;
                areaList.forEach(function (art) {
                  areaNameString += "<option value=" + art.areaName + ">" + art.areaName + "</option>"
                });
                return false;
              }
            });
            return false;
          }
        });
        $("#areaName").append(areaNameString);
        $("#areaName").select2('val', areaList[0].areaName);
      }
      $("#payway").select2();
      $("#pickway").select2();
      var remark = '';
      var remarkIsSave = false;
      var totalPrice = 0;
      $("#pickway").change(function(e){
          var type = $(this).val();
          if (type == 'Logistics') {
            remarkIsSave = false;
            $("#box-config").modal("show");
          }
      });
      $('#box-config').on('hidden.bs.modal', function (e) {
        if (!remarkIsSave) {
          // 关闭填写地址
          $("#pickway").select2('val', 'SinceLift');
        }
      });
      $("#box-config").find(".bt-save").click(function() {
        if (wizform.valid() == false) {
          return false;
        }
        remark = {};
        remark.receiver=$("#box-config [name=receiver]").val();
        remark.provinceName=$("#box-config [name=provinceName]").val();
        remark.cityName = $("#box-config [name=cityName]").val();
        remark.areaName = $("#box-config [name=areaName]").val();
        remark.address = $("#box-config [name=address]").val();
        remark.telPhone = $("#box-config [name=telPhone]").val();
        remarkIsSave = true;
        console.log(remark);
        $("#box-config").modal('hide');
      });
      var wizform = $('#form_account');
      wizform.validate({
        doNotHideMessage: true,
        errorClass: 'error-span',
        errorElement: 'span',
        rules: {
          receiver: {
            required: true
          },
          telPhone: {
            required: true
          },
          provinceName: {
            required: true
          },
          cityName: {
            required: true
          },
          areaName: {
            required: true
          },
          address: {
            required: true
          }
        },
        highlight: function (element) {
          $(element)
            .closest('.form-group').removeClass('has-success').addClass('has-error');
        },

        unhighlight: function (element) {
          $(element)
            .closest('.form-group').removeClass('has-error');
        },
        success: function (label) {
          label.addClass('valid')
            .closest('.form-group').removeClass('has-error').addClass('has-success');
        }
      });
      var actionId = $.getUrlParam("id");
      var actionName = $.getUrlParam("actionName");

      $(".sale_report").click(function () {
        window.location.href = "sales_report.html?actionId=" + actionId + "&actionName=" + actionName;
      })

      $("input[name=actionName]").val(actionName);

      $("[name=skuCode]").focus();

      var domain = window.location.href.substr(0, window.location.href.indexOf("pages"));
      //delete
      var delTr = function () {
        var $tr  = $(this).closest("tr"),
            $sibs =  $tr.siblings(),
            skuInfos = [];
        $sibs.each(function (index, item) {
            var obj = {};
            obj.skuCode = $(this).find(".skuCode").html();
            obj.productAmount = parseInt($(this).find(".amount").html())
            skuInfos.push(obj);
        });        
        skuInfos = JSON.stringify(skuInfos);
        // computerAmount();
        $.ajax({
          type: "post",
          url: domain + "/admin/action/addProductByBarCode.do",
          data: {
            barCode: '',
            actionId: actionId,
            skuInfos: skuInfos
          },
          async: true,
          success: function (result) {
            if (result.type != 'success' || result == '' || result.extra == "") {
              $.alert("删除商品失败！")
              return false;
            };
            totalPrice = result.extra.totalPrice;
            $(".totalMoney").html(formatNumber(totalPrice, 2, ','));
            $tr.remove();
            computerAmount();
          }
        });
      }
      var computerAmount = function () {
        var totalAmount = 0;
        //var totalMoney = 0;
        $("table tbody tr").each(function (index, item) {
          var amount = $(this).find(".amount").html();
          //var price = $(this).find(".salesprice").html();
          totalAmount += parseInt(amount);
          //totalMoney += parseFloat(amount * price);
        });
        $(".totalAmount").html(totalAmount);
        //$(".totalMoney").html(formatNumber(totalMoney, 2, ','));
      };
      var formatNumber = function (num, cent, isThousand) {
					num = num.toString().replace(/\$|\,/g, '');
					// 检查传入数值为数值类型  
					if (isNaN(num))
						num = "0";
					// 获取符号(正/负数)  
					sign = (num == (num = Math.abs(num)));
					num = Math.floor(num * Math.pow(10, cent) + 0.50000000001);  // 把指定的小数位先转换成整数.多余的小数位四舍五入  
					cents = num % Math.pow(10, cent);              // 求出小数位数值  
					num = Math.floor(num / Math.pow(10, cent)).toString();   // 求出整数位数值  
					cents = cents.toString();               // 把小数位转换成字符串,以便求小数位长度  
					// 补足小数位到指定的位数  
					while (cents.length < cent)
						cents = "0" + cents;
					if (isThousand) {
						// 对整数部分进行千分位格式化.  
						for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
							num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
					}
					if (cent > 0)
						return (((sign) ? '' : '-') + num + '.' + cents);
					else
						return (((sign) ? '' : '-') + num);
        }
      function getSkuInfos () {
        var getSkuInfos = [];
        $("table tbody tr").each(function (index, item) {
            var obj = {};
            obj.skuCode = $(this).find(".skuCode").html();
            obj.productAmount = parseInt($(this).find(".amount").html())
            getSkuInfos.push(obj);
        });
        return JSON.stringify(getSkuInfos);
      }
      //注册skuCode keypress 事件
      $("[name=skuCode]").keypress(function (e) {
        var ev = document.all ? window.event : e;
        if (ev.keyCode == 13) {
          if ($("[name=skuCode]").val() == "") {
            alert("请输入条形码");
            return false;
          }
          $.ajax({
            type: "post",
            url: domain + "/admin/action/addProductByBarCode.do",
            data: {
              barCode: $("[name=skuCode]").val(),
              actionId: actionId,
              skuInfos: getSkuInfos()
            },
            async: true,
            success: function (result) {
              if (result.type != 'success' || result == '' || result.extra == "") {
                alert("请输入正确条码");
                return false;
              }
              var product = result.extra.product;
              var skuCode = product.skuCode;
              var isExist = false;
              var isStock = false;
              $("table tbody tr").each(function (index, item) {
                if ($(this).find(".skuCode").html() == skuCode) {
                  isExist = true;
                  var stockAmount = $(this).find(".stockamount").html();
                  var amount = parseInt($(this).find(".amount").html()) + 1;
                  if (stockAmount < amount) {
                    alert("商品库存不足");
                    isStock = true;
                    return false;
                  }
                  $(this).find(".amount").html(amount);
                }
              });
              if ( isStock ) {
                return false;
              }
              if (!isExist) {
                if (product.amount < 1) {
                  alert("商品库存不足");
                  return false;
                }
                var str = "<td class='skuCode'>" + product.skuCode + "</td>";
                str += "<td class='productName'>" + product.productName + "</td>";
                str += "<td class='size'>" + product.size + "</td>";
                str += "<td class='salesprice' style='color:red'>" + product.salesPrice + "</td>";
                str += "<td class='amount'>1</td>";
                str += "<td class='stockamount'>" + product.amount + "</td>";
                str += "<td><a class='btn btn-danger'>删除</a></td>";
                $("table tbody").append("<tr>" + str + "</tr>");

              }
              computerAmount();
              totalPrice = result.extra.totalPrice;
              $(".totalMoney").html(formatNumber(totalPrice, 2, ','))
              $("[name=skuCode]").val("");
              $(".btn-danger").unbind("click").click(delTr);
            }

          });
        }

      });

      //提交订单
      $(".bt-saveOrder").click(function () {
        if ($("table tbody tr").length == 0) {
          alert("请先录入商品数据");
          return false;
        }
        var order = [];


        $("table tbody tr").each(function (index, item) {
          var orderdetail = {};
          orderdetail.actionId = actionId;
          orderdetail.payType = $("[name=payType]:checked").val();
          orderdetail.totalMoney = $(".totalMoney").html();
          orderdetail.skuCode = $(this).find(".skuCode").html();
          orderdetail.productName = $(this).find(".productName").html();
          orderdetail.size = $(this).find(".size").html();
          orderdetail.salesPrice = $(this).find(".salesprice").html();
          orderdetail.amount = $(this).find(".amount").html();
          order.push(orderdetail);
        });
        var payType = $("#payway").select2('val');
        var pickWay = $("#pickway").select2('val');
        if (pickWay == 'Logistics') {
          remark = JSON.stringify(remark);
        } else {
          remark = '';
        }
        $.confirm("确认提交订单，提交后无法撤回!", function () {
          $.ajax({
            type: "post",
            url: domain + "admin/action/saveOrder.do",
            data: $.param({ 
              order: JSON.stringify(order),
              remark: remark,
              pickWay: pickWay,
              payType: payType
            }),
            async: true,
            success: function (result) {
              if (result.type == "success") {
                alert("提交成功");
                $("table tbody").empty();
                $(".totalAmount").html("0");
                $(".totalMoney").html("0");
                $("#box-config [name=receiver]").val('');
                //$("#box-config [name=provinceName]").val('');
                // $("#box-config [name=areaName]").val('');
                // $("#box-config [name=cityName]").val('');
                $("#box-config [name=address]").val('');
                $("#box-config [name=telPhone]").val('');
                $("#pickway").select2('val', 'SinceLift');
                $("#payway").select2('val', 'Cash');
                remarkIsSave = false;
                remark = '';
              }
            }
          });


        });


      });


    });
  </script>
</body>

</html>